<template>
  <div>
    <h1>审核状态</h1>
    <ul>
      <li v-for="(status, index) in statuses" :key="index">{{ status }}</li>
    </ul>
  </div>
</template>

<script>
import {EventSourcePolyfill} from "event-source-polyfill";

export default {
  data() {
    return {
      statuses: [],
      eventSource: null
    };
  },
  mounted() {
    this.connectToSse();
  },
  beforeUnmount() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  },
  beforeDestroy() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  },
  methods: {
    connectToSse() {
      console.log('baseApi' + import.meta.env.VITE_SPRING_BOOT_BASE_API);

      this.eventSource = new EventSourcePolyfill(import.meta.env.VITE_SPRING_BOOT_BASE_API + '/sse/status'
          , {
            headers: {
              'Authorization': "token"
            },
            heartbeatTimeout: 34200000
          }
      );
      this.eventSource.onopen = function () {
        console.log('EventSource connection opened.');
      };

      this.eventSource.onmessage = (event) => {
        const data = JSON.parse(event.data);
        console.log(data[1].data);

        this.statuses.push(data[1].data);
      };

      // eventSource.readyState.onchange = (event) => {
      //   console.log("EventSource readyState:", event.readyState);
      // };
      this.eventSource.onerror = (err) => {
        console.error("EventSource failed1:", err);
        // EventSource.CONNECTING
        this.eventSource.close(); // 关闭出错的连接
        this.eventSource = null; // 重置eventSource变量，允许重建连接
      };
    }
  }
};
</script>

<style scoped>
ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
</style>
